package com.hqhsc.module.manage.system.service;

import com.hqhsc.core.cache.CacheKey;
import com.hqhsc.module.common.dao.CommonDao;
import com.hqhsc.module.common.domain.Menu;
import com.hqhsc.module.common.service.CommonService;
import com.hqhsc.module.common.service.ManageMemcacdedClient;
import com.hqhsc.module.init.service.InitService;
import com.hqhsc.module.log.service.LogService;
import com.hqhsc.module.login.domain.User;
import com.hqhsc.module.manage.system.dao.SystemManageDao;
import com.hqhsc.module.manage.system.domain.Org;
import com.hqhsc.utils.DateUtil;
import com.hqhsc.utils.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 *
 * @author jiangyin
 */
@Service
public class SystemManageService {

	static Logger logger = LoggerFactory.getLogger(SystemManageService.class);

	@Autowired
	private ManageMemcacdedClient memcachedClient;
	@Autowired
	private SystemManageDao systemManageDao;
    @Autowired
    private CommonService commonService;
    @Autowired
    private InitService initService;
    @Autowired
    private CommonDao commonDao;
    @Autowired
    private LogService logService;

    public Map<String , Object> getUserList(long org_id , String user_name , int start , int size) {

        long total = this.systemManageDao.getUserCount(org_id, user_name);
        List<User> user_list = this.systemManageDao.getUserList(org_id, user_name, start, size);

        Map<String , Object> map = new HashMap<String, Object>();
        map.put("total" , total);
        map.put("user_list" , user_list);
        return map;
    }

    public int userDoAdd(long userid , String login_name, String login_pwd, String user_name, String nick_name , String org_id , String role_id , String employee_id) {
        int check = this.systemManageDao.checkUserName(login_name);
        int result = 0;
        if(check == 0) {
            String login_pwd_md5 = MD5Util.MD5Encrypt(login_pwd);
            long add_userid = commonDao.getNextVal("UsersSeq");
            result = this.systemManageDao.inertUser(add_userid , login_name , login_pwd_md5 , user_name , nick_name , userid , DateUtil.date2String(new Date()) , employee_id);
            if(result == 1) {//成功以后，将该用户角色和组织对应起来
                this.systemManageDao.insertUserRole(add_userid , Long.valueOf(role_id) , Long.valueOf(org_id));
            }
            logService.insertLog(userid , "新增管理员"+add_userid , "");
        }
        return result;
    }

    /**
     * 修改用户
     * @param user_name
     * @return
     */
    public int userDoEdit(long userid , String user_name , long edited_user_id , String employee_id , String nick_name) {
        int result = this.systemManageDao.editUser(edited_user_id , user_name , userid , employee_id , nick_name);
        if(result > 0) {
            logService.insertLog(userid , "更新管理员"+edited_user_id , "");
        }
        return result;
    }


    /**
     * 删除用户
     * @param userid
     * @param edited_user_id
     * @return
     */
    public int userDoDelete(long userid , long edited_user_id) {
        int result = this.systemManageDao.deleteUser(edited_user_id);
        if(result > 0) {
            logService.insertLog(userid , "删除管理员"+edited_user_id , "");
        }
        return result;
    }


    public Map<String , Object> getOrgList(String org_name , int start , int size) {

        long total = this.systemManageDao.getOrgCount(org_name);
        List<Org> org_list = this.systemManageDao.getOrgList(org_name, start, size);

        Map<String , Object> map = new HashMap<String, Object>();
        map.put("total" , total);
        map.put("org_list" , org_list);
        return map;
    }

    public int orgDoAdd(String org_name , String org_address , long user_id) {
        return this.systemManageDao.orgDoAdd(org_name , org_address , user_id);
    }





    public Map<String , List<Menu>> getRoleMenuList(long role_id) {
        Map<String , List<Menu>> map = new HashMap<String, List<Menu>>();
        List<Menu> top_menu_list = new ArrayList<Menu>();//顶层菜单
        List<Menu> sub_menu_list = new ArrayList<Menu>();//子菜单

        List<Menu> sys_menu_list = this.initService.getSysMenu();
        List<Menu> role_menu_list = this.commonService.getRoleMenuList(role_id);//角色对应菜单
        for(Menu sys_menu : sys_menu_list) {
            for(Menu role_menu : role_menu_list) {
                if(sys_menu.getMenu_id() == role_menu.getMenu_id()) {
                    sys_menu.setRole_menu_status(1);
                }
            }
        }

        for(Menu menu : sys_menu_list) {
            if(menu.getPid() == 0) {//顶层菜单
                if(!top_menu_list.contains(menu)) {//顶层菜单列表中没有该菜单，将该菜单加入到顶层菜单列表中
                    top_menu_list.add(menu);
                }
            } else {
                sub_menu_list.add(menu);
            }
        }
        map.put("top_menu_list" , top_menu_list);
        map.put("sub_menu_list" , sub_menu_list);

        return map;

    }

    /**
     * 执行角色对应菜单权限配置
     * @param sub_menu_ids
     * @param role_id
     * @return
     */
    public int roleMenuDoConfig(String sub_menu_ids , long role_id , long userid) {
        if(sub_menu_ids.length() > 0) {
            //找到子菜单对应的父菜单
            String[] sub_menu_arr = sub_menu_ids.substring(0 , sub_menu_ids.length()-1).split(",");
            List<Long> top_menu_list = new ArrayList<Long>();
            for(int i = 0 ; i < sub_menu_arr.length ; i++) {
                String sub_menu_id_str = sub_menu_arr[i];
                String top_menu_id_str = sub_menu_id_str.substring(0 , sub_menu_id_str.length()-2) + "00";
                Long top_menu_id = Long.valueOf(top_menu_id_str);
                if(!top_menu_list.contains(top_menu_id)) {
                    top_menu_list.add(top_menu_id);
                }
            }
            String all_menu_id = sub_menu_ids.substring(0 , sub_menu_ids.length()-1);
            for(int i = 0 ; i < top_menu_list.size() ; i++) {
                all_menu_id = all_menu_id + "," + top_menu_list.get(i);
            }

            this.systemManageDao.roleMenuDoConfig(all_menu_id.split(","), role_id);
        } else {//该角色不配置菜单，则删除该角色所有菜单
            this.systemManageDao.deleteRoleMenu(role_id);
        }

        String key = CacheKey.getRoleMenuListKey(role_id);
        memcachedClient.delete(key);

        logService.insertLog(userid , "配置角色对应菜单权限"+role_id , sub_menu_ids);

        return 1;
    }


    public int doModifyPassword(String old_password , String new_password , String confirm_password , String user_current_password , long user_id) {
        if(!MD5Util.MD5Encrypt(old_password).equals(user_current_password)) {
            return -1;
        }
        if(!new_password.equals(confirm_password)) {
            return -2;
        }

        String password_md5 = MD5Util.MD5Encrypt(new_password);
        logService.insertLog(user_id , "修改密码"+user_id , "new_password");
        return this.systemManageDao.doResetPassword(user_id , password_md5);
    }

}
